//
//  BGSetViewController.m
//  bigMall
//
//  Created by ios on 16/7/18.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGSetViewController.h"
#import "BGLoginViewController.h"
#import "BGDateResult.h"
#import "BGXGpwdController.h"
#import "BGFindpayController.h"
#import "BGFindPwdViewController.h"
#import "BGXGpayController.h"
#import "SDImageCache.h"
#import "BGXGphoneController.h"

@interface BGSetViewController () <UITableViewDelegate,UITableViewDataSource> {
    
    UITableView *_tableView;
    NSArray *_arr;
    UIButton *_btn;
    
}
@property (nonatomic,copy) NSString *clearCacheName;
@end

@implementation BGSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"设置";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *backIetm = [[UIBarButtonItem alloc] init];
    backIetm.title =@"";
    self.navigationItem.backBarButtonItem = backIetm;
    
    [self createUi];
    
    [self initArr];
    
    [self changeBtn];
    
}

- (void)changeBtn {
    
    NSString *state = [[NSUserDefaults standardUserDefaults]objectForKey:State];
    
    if ([state isEqualToString:StateValue] ) {
        
        _btn.hidden = NO;
        [_btn setTitle:@"退出当前账户" forState:UIControlStateNormal];
        [_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_btn setBackgroundColor:[UIColor redColor]];
        
        [_btn addTarget:self action:@selector(tuichu) forControlEvents:UIControlEventTouchUpInside];
        
    }else {
        
        _btn.hidden = YES;
//        [_btn setTitle:@"马 上 登 陆" forState:UIControlStateNormal];
//        _btn.titleLabel.textAlignment = NSTextAlignmentCenter;
//        [_btn setBackgroundColor:[UIColor redColor]];
//        [_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [_btn addTarget:self action:@selector(denglu) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
}

- (void)tuichu {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"退出登陆" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [BGDateResult loginOutSuccess:^(NSString *status, NSString *msg, NSString *res) {
            
            [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:State];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [self.navigationController popViewControllerAnimated:YES];
            
        } failure:^(NSError *error) {
            
        }];

    }];

    [alert addAction:action];
    
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:cancle];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
}

- (void)denglu {
    
//    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:State];
//    
//    [[NSUserDefaults standardUserDefaults] synchronize];
    
    BGLoginViewController *login = [[BGLoginViewController alloc] init];
    
    self.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:login animated:YES];
    
}

- (void)initArr {
    
    _arr = @[@"登录密码设置",@"手机号设置",@"支付密码设置",@"支付密码找回",@"清除缓存",@"版本信息"];
    
}

- (void)createUi {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, BGWidth, BGHight - 70) style:UITableViewStyleGrouped];
    
    _tableView.delegate = self;
    
    _tableView.dataSource = self;

    [self.view addSubview:_tableView];
    
    _btn = [[UIButton alloc] initWithFrame:CGRectMake(20, self.view.bounds.size.height - 60, self.view.bounds.size.width - 40, 50)];
    
    _btn.clipsToBounds = YES;
    
    _btn.layer.cornerRadius = 10;
    
    [self.view addSubview:_btn];
    
}

#pragma mark - delegate - datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _arr.count;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"celId"];
    
    UITableViewCell *cel = [tableView dequeueReusableCellWithIdentifier:@"celId" forIndexPath:indexPath];
    
    cel.textLabel.text = _arr[indexPath.row];
    
    cel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    if (indexPath.row == 5) {
        
        cel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 90, 10, 50, 30)];
        
        //获取当前的版本信息
        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        
        lab.text = version;
        
        [cel addSubview:lab];
        
        lab.textAlignment = NSTextAlignmentRight;
        
    }
        
        cel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cel;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            BGXGpwdController *a = [[BGXGpwdController alloc] init];
            
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:a animated:YES];
//            self.navigationController.hidesBottomBarWhenPushed = NO;

        } else if (indexPath.row == 1) {
            
            BGXGphoneController *a = [[BGXGphoneController alloc] init];
            self.hidesBottomBarWhenPushed = YES;

            [self.navigationController pushViewController:a animated:YES];
//            self.hidesBottomBarWhenPushed = NO;

        } else if (indexPath.row == 2) {
            
            BGXGpayController *a = [[BGXGpayController alloc] init];
            self.hidesBottomBarWhenPushed = YES;

            [self.navigationController pushViewController:a animated:YES];
//            self.hidesBottomBarWhenPushed = NO;

        } else if (indexPath.row == 3) {
        
        BGFindpayController * a = [[BGFindpayController alloc] init];
        self.hidesBottomBarWhenPushed = YES;

        [self.navigationController pushViewController:a animated:YES];
//        self.hidesBottomBarWhenPushed = NO;

        } else if (indexPath.row == 4) {
            
            [self cleanCache];
            
        }
        }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)cleanCache {
    
    NSString *cacheStar = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清除缓存" message:[NSString stringWithFormat:@"%.4fM",[self folderSizeAtPath:cacheStar]] preferredStyle:UIAlertControllerStyleAlert];
    
    //确定
    UIAlertAction *determine = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self clearCache:cacheStar];
        
    }];
    
    //取消
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        
    }];
    
    [alert addAction:cancle];
    [alert addAction:determine];
    [self presentViewController:alert animated:YES completion:nil];
    
}
- (float)folderSizeAtPath:(NSString *)path{
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            long long size=[fileManager attributesOfItemAtPath:absolutePath error:nil].fileSize;
            folderSize += size/1024.0/1024.0;
        }
        //SDWebImage框架自身计算缓存的实现
        folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        return folderSize;
    }
    return 0;
    
}
- (void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
